<template>
  <div v-loading="loading">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 栅格系统 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="$router.push('goodsadd')">添加商品</el-button>
        </el-col>
      </el-row>
      <el-table :data="goods" border stripe>
        <el-table-column label="#" type="index" width="50px"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格（元）" prop="goods_price" width="120px"></el-table-column>
        <el-table-column label="商品数量" prop="goods_number" width="85px"></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight" width="85px"></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="160px">
          <template slot-scope="scope">
            {{ (scope.row.add_time * 1000) | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editGoods(scope.row.goods_id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeById(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 修改商品对话框 -->
      <el-dialog title="修改商品信息" :visible.sync="editGoodsDialogVisible" width="35%">
        <el-form :model="editForm">
          <el-form-item label="商品名称">
            <el-input type="textarea" v-model="editForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="editForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量">
            <el-input v-model="editForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量">
            <el-input v-model="editForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="选择分类">
            <el-cascader
              v-model="editForm.goods_cat"
              :options="cateList"
              :props="{
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id'
              }"
              @change="handleChange"
            >
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editGoodsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditGoods">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {

  name: 'Goods',
  data () {
    return {
      loading: false,
      queryInfo: {
        query: '', // 查询关键字
        pagenum: 1, // 当前页，默认显示第一页
        pagesize: 10 // 每页数据条数 数据不多
      },
      total: 0,
      value: '',
      goods: [],
      editGoodsDialogVisible: false,
      nowTime: '',
      editForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        pics: [], // 上传图片的临时路径
        goods_introduce: '',
        attrs: []
      },
      cateList: []
    }
  },
  created () {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList () {
      const { data: res } = await this.$http.get('goods', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败')
      // this.$message.success('获取商品列表成功！')
      // console.log(res.data)
      this.goods = res.data.goods
      // console.log(this.goods)
      this.total = res.data.total
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getGoodsList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getGoodsList()
    },
    handleChange () {
      if (this.editForm.goods_cat.length < 3) {
        this.editForm.goods_cat = []
        this.$message.error('请选择三级分类')
      }
    },
    // 修改商品信息
    async editGoods (id) {
      this.getCateList()
      // console.log(id)
      this.nowTime = new Date().getTime()
      const { data: res } = await this.$http.get(`goods/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败')
      // console.log(res.data)
      this.editForm = res.data
      this.editGoodsDialogVisible = true
    },
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败！')
      this.cateList = res.data
      // console.log(this.cateList)
    },
    // 修改确定按钮  还有问题
    async saveEditGoods () {
      // const { data: res } = await this.$http.put(`goods/${this.editForm.goods_id}`, editForm)
      // if (res.meta.status !== 200) return this.$message.error('修改失败！')
      // this.$message.success('修改成功！')
      // this.getGoodsList()
      // this.editGoodsDialogVisible = false

      var form = _.cloneDeep(this.addForm)
      // console.log(form)
      const { data: res } = await this.$http.put(`goods/${form.cat_id}`, form)
      if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
      this.$message.success('添加商品成功！')
    },
    // 删除按钮事件
    removeById (id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`goods/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除商品失败')
        this.$message.success('删除成功！')
        this.getGoodsList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
</style>
